package com.starry.androidmvvmexample

import android.app.Application
import android.util.Log
import androidx.lifecycle.HasDefaultViewModelProviderFactory
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class App(
) : Application(), ViewModelStoreOwner, HasDefaultViewModelProviderFactory {

    /**
     * 实现ViewModelStoreOwner、HasDefaultViewModelProviderFactory，
     * 使App具备存储、提供ViewModel的能力，使得各Activity或Fragment公用同一个ViewModel对象
     */
    override val viewModelStore: ViewModelStore by lazy {
        ViewModelStore()
    }
    override val defaultViewModelProviderFactory: ViewModelProvider.Factory by lazy {
        ViewModelProvider.AndroidViewModelFactory.getInstance(this)
    }


    override fun onCreate() {
        super.onCreate()
        baseInit()
        onSyncInit()
        onAsyncInit()

    }

    /**
     * 初始化时需要执行的基本任务
     */
    private fun baseInit() {
        Log.i("lixu", "baseInit: ${Thread.currentThread()}")
    }

    /**
     * 必须同步初始化的任务
     */
    private fun onSyncInit() {
        Log.i("lixu", "onSyncInit: ${Thread.currentThread()}")
    }

    /**
     * 可以异步初始化的任务
     */
    private fun onAsyncInit() {
        // 使用 ProcessLifecycleOwner 的协程作用域（与进程生命周期绑定）
        ProcessLifecycleOwner.get().lifecycleScope.launch(Dispatchers.IO) {
            // 执行耗时初始化（如数据库、网络请求）
            // todo
            Log.i("lixu", "onAsyncInit: ${Thread.currentThread()}")
        }
    }

}